package com.keyue.isolate.handler;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.keyue.common.constant.Constant;
import com.keyue.isolate.constant.DataIsolateConstants;
import com.keyue.isolate.context.DataIsolateValue;
import com.keyue.isolate.context.IsolateTableConfigVO;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.IsNullExpression;
import net.sf.jsqlparser.expression.operators.relational.LikeExpression;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.util.cnfexpression.MultiOrExpression;

import java.util.ArrayList;
import java.util.List;

public class OrLikeDataIsolateExpStragegy extends DataIsolateExpStragegy {

    public static final DataIsolateExpStragegy SINGLE_INSTANCE = new OrLikeDataIsolateExpStragegy();

    @Override
    Expression parse(DataIsolateValue dataIsolateValue, String prefix, IsolateTableConfigVO configVO) {
        List<String> codes = getCodes(dataIsolateValue, configVO.getDataIsolateColumnName());
        if (CollectionUtils.isEmpty(codes) || codes.stream().anyMatch(x -> x.equalsIgnoreCase(Constant.ALL))) {
            return null;
        }
        List<Expression> expressions = new ArrayList<>(codes.size());
        Column column = new Column(prefix + configVO.getTableColumnName());
        for (String code : codes) {
            if (DataIsolateConstants.NULL_VALUE_CODE.equals(code)) {
                IsNullExpression isNullExpression = new IsNullExpression();
                isNullExpression.setLeftExpression(column);
                expressions.add(isNullExpression);
                continue;
            }

            LikeExpression likeExpression = new LikeExpression();
            likeExpression.setLeftExpression(column);
            likeExpression.setRightExpression(new StringValue("%" + code + "%"));
            expressions.add(likeExpression);
        }

        return new MultiOrExpression(expressions);
    }
}
